Page({

  /**
   * 页面的初始数据
   */
  data: {
    historyList:[],
    productList:[],
    total:0,
    keyword:"",
    noData:false,
    loading:false,
    page: 1,
    pageSize: 10,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let searchKeyArr = wx.getStorageSync('searchKeyArr') || null;
    if(searchKeyArr){
      this.setData({
       historyList:searchKeyArr
      })
    }
 },

  //输入框改变的时候
  onChange(e){  
    this.setData({
      keyword:e.detail
    })
  },
  //清空输入框
  onClear(){
    this.setData({
      noData:false,
      keyword:"",
      productList:[],
      total:0
    })
  },

   //清空搜索历史
   removeHistory(){
    this.setData({
      noData:false,
      historyList:[],
      total:0,
      keyword:"",
      productList:[]
    })
    wx.removeStorageSync('searchKeyArr')
 },

  //确认搜索
  onSearch(){
    const keyword = this.data.keyword.trim();
    if (!keyword) {
      wx.showToast({ title: '请输入关键词', icon: 'none' });
      return;
    }
    console.log(this.data.keyword);
    let hisArr = this.data.historyList || [];
    hisArr.unshift(this.data.keyword);
    hisArr = [...new Set(hisArr)];
    hisArr = hisArr.slice(0,10)
    this.setData({
      historyList:hisArr
    })
    wx.setStorageSync('searchKeyArr', hisArr);

    this.setData({ page: 1, hasMore: true })
    this.getData()
  },

  async getData(isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) return
  
    const newPage = isLoadMore ? this.data.page + 1 : 1
    this.setData({ loading: true })
  
    try {
      const res = await wx.cloud.callFunction({
        name: 'getAllData',
        data: {
          keyword: this.data.keyword,
          page: newPage,
          pageSize: this.data.pageSize
        }
      })
  
      // 字段重映射处理
      const processedData = (res.result.data || []).map(item => {
        const base = { 
          id: item._id || item.id || Date.now(),
          sourceData: item // 保留原始数据
        }
  
        switch (item.type) {
          case 'ecology':
            return {
              ...base,
              type: 'ecology',
              name: item.text || '未知生态项目',
              photo: item.img || '/images/default-ecology.png'
            }
  
          case 'poi':
            return {
              ...base,
              type: 'poi',
              name: item.name || '未命名场点',
              photo: item.photos?.[0]?.url || ''
            }
  
          case 'venue':
            return {
              ...base,
              type: 'venue',
              name: item.className || '未命名场地',
              photo: item.img || ''
            }
  
        case 'food':
          return {
            ...base,
            type: 'food',
            name: item.food_name || '神秘食物',
            photo: item.food_image || ''
          }
        
        case 'story':
          return {
            ...base,
            type: 'story',
            name: item.title || '未命名标题',
            detail:item.detail || ''
          }

          default:
            return {
              ...base,
              type: 'unknown',
              name: '未知类型',
              photo: ''
            }
        }
      })
  
      const noData = processedData.length === 0 && !isLoadMore
      const hasMore = res.result.hasMore && processedData.length >= this.data.pageSize
      console.log('processedData，res',processedData,res.result);
      this.setData({
        productList: isLoadMore 
          ? [...this.data.productList, ...processedData] 
          : processedData,
        page: newPage,
        hasMore,
        noData,
        loading: false,
        total: res.result.visibleTotal || 0
      })
  
    } catch (err) {
      console.error('请求失败:', err)
      this.setData({ 
        loading: false,
        hasMore: true // 出错时保持可加载状态
      })
      wx.showToast({ 
        title: err.errMsg || '加载失败', 
        icon: 'none',
        duration: 2000
      })
    }
  },
// 上拉加载更多
onReachBottom() {
  console.log(this.data.hasMore,this.data.loading,this.data.productList.length);
  if (this.data.hasMore && !this.data.loading) {
    console.log('触发加载更多')
    this.getData(true)
  }
},

   //点击搜索历史的每一项
   tapHisItem(e){
    console.log(e);
    this.setData({
      keyword:e.currentTarget.dataset.value
    })
    this.getData();
  },
   // 跳转到详情页面
   goToDetail(e) {
    const { item } = e.currentTarget.dataset;
    if (item.type === 'poi') {
      wx.navigateTo({
        url: `/pages/mapInfo/mapInfo?id=${item.id}`
      });
    } else if(item.type==='ecology'){
      wx.navigateTo({
        url: `/pages/ecology/ecology?name=${item.name}`
      });
    }else if(item.type === 'venue'){
      wx.navigateTo({
        url: `/pages/venuesInfo/venuesInfo?id=${item.id}`
      });
    }else if(item.type === 'food'){
      wx.navigateTo({
        url: `/pages/foodDetail/foodDetail?id=${item.id}`
      });
    }else if(item.type === 'story'){
      wx.navigateTo({
        url: `/pages/stroyDetail/stroyDetail?id=${item.id}`,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})